﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using ifunction.Fiddler.Model;
using MongoDB.Driver;

namespace ifunction.Fiddler.ServiceCore
{
    public class FiddlerSimulatorServiceCore
    {
        /// <summary>
        /// The package file path
        /// </summary>
        protected const string packageFilePath = "packages.dat";

        /// <summary>
        /// The mongo_collection_ package
        /// </summary>
        protected const string mongo_collection_Package = "Package";

        /// <summary>
        /// The mongo_collection_ request log
        /// </summary>
        protected const string mongo_collection_RequestLog = "RequestLog";

        /// <summary>
        /// The packages
        /// </summary>
        protected static List<RuntimePackage> packages = null;

        /// <summary>
        /// The locker
        /// </summary>
        protected static object locker = new object();

        /// <summary>
        /// The mongo database
        /// </summary>
        protected MongoDatabase mongoDatabase;

        /// <summary>
        /// Initializes a new instance of the <see cref="FiddlerSimulatorServiceCore"/> class.
        /// </summary>
        public FiddlerSimulatorServiceCore(MongoDatabase mongoDB = null)
        {
            Initialize();
            mongoDatabase = mongoDB;
        }

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        protected static void Initialize()
        {
            if (packages == null)
            {
                lock (locker)
                {
                    if (packages == null)
                    {
                        LoadPackagesWithoutLocker();
                    }
                }
            }
        }

        /// <summary>
        /// Gets the packages.
        /// </summary>
        /// <returns>List{RequestPackage}.</returns>
        /// <exception cref="System.InvalidOperationException">Error occurred for method: GetPackages</exception>
        public List<RequestPackage> GetPackages()
        {
            List<RequestPackage> result = new List<RequestPackage>();

            try
            {
                lock (locker)
                {
                    foreach (var one in packages)
                    {
                        result.Add(one.ToRequestPackage());
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Error occurred for method: GetPackages", ex);
            }

            return result;
        }

        public Guid AddOrUpdatePackage(RequestPackage package)
        {
            throw new NotImplementedException();
        }

        public void RemovePackage(Guid key)
        {
            var package = this.GetRuntimePackageByKey(key);

            if (package != null)
            {
                lock (locker)
                {

                }
            }
        }

        public List<RequestLog> QueryRequestLogs(RequestLogCriteria criteria)
        {
            List<RequestLog> result = new List<RequestLog>();

            return result;
        }

        /// <summary>
        /// Loads the packages without locker.
        /// </summary>
        /// <param name="mongoDatabase">The mongo database.</param>
        /// <exception cref="System.InvalidOperationException">Error occurred for method: SavePackagesWithoutLocker</exception>
        protected static void LoadPackagesWithoutLocker(MongoDatabase mongoDatabase = null)
        {
            try
            {
                IEnumerable<RequestPackage> requestPackageList = null;

                if (mongoDatabase == null)
                {
                    object list = null;

                    if (File.Exists(packageFilePath))
                    {
                        byte[] bytes = File.ReadAllBytes(packageFilePath);
                        using (MemoryStream memoryStream = new MemoryStream(bytes, 0, bytes.Length))
                        {
                            BinaryFormatter formatter = new BinaryFormatter();
                            list = formatter.Deserialize(memoryStream);
                        }
                    }

                    if (list != null)
                    {
                        requestPackageList = list as List<RequestPackage>;
                    }
                }
                else
                {
                    var collection = mongoDatabase.GetCollection<RequestPackage>(mongo_collection_Package);
                    requestPackageList = collection.FindAll();
                }

                packages.Clear();
                if (requestPackageList != null)
                {
                    foreach (var one in requestPackageList)
                    {
                        packages.Add(one.ToRuntimePackage());
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Error occurred for method: SavePackagesWithoutLocker", ex);
            }
        }

        /// <summary>
        /// Saves the packages without locker.
        /// </summary>
        protected static void SavePackagesWithoutLocker(MongoDatabase mongoDatabase = null)
        {
            try
            {
                List<RequestPackage> requestPackages = new List<RequestPackage>();

                foreach (var one in packages)
                {
                    requestPackages.Add(one.ToRequestPackage());
                }

                if (mongoDatabase == null)
                {
                    BinaryFormatter formatter = new BinaryFormatter();

                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        formatter.Serialize(memoryStream, requestPackages);

                        File.WriteAllBytes(packageFilePath, memoryStream.ToArray());
                    }
                }
                else
                {
                    var collection = mongoDatabase.GetCollection<RequestPackage>(mongo_collection_Package);



                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Error occurred for method: SavePackagesWithoutLocker", ex);
            }
        }

        /// <summary>
        /// Gets the runtime package by key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns>RuntimePackage.</returns>
        protected RuntimePackage GetRuntimePackageByKey(Guid key)
        {
            RuntimePackage result = null;

            lock (locker)
            {
                foreach (var one in packages)
                {
                    if (one.Key == key)
                    {
                        result = one;
                        break;
                    }
                }
            }

            return result;
        }
    }
}
